import Mock from 'mockjs';
const Random = Mock.Random;
// 设置全局延时，模拟网络请求时间
Mock.setup({
	timeout: '500',
});
const createResponse = (code, message, data) => ({
	code,
	message,
	data,
	timestamp: Date.now(),
});

Mock.mock('/auth/login', 'post', options => {
	const { username, password } = JSON.parse(options.body);

	if (username === 'admin' && password === '123456') {
		const data = {
			token: Random.guid(),
			userId: Random.id(),
			username: username,
			role: 'admin',
		};
		return createResponse(200, '登录成功', data);
	} else {
		return {
			code: 401,
			message: '用户名或密码错误',
			data: null,
		};
	}
});

// 模拟注册接口
Mock.mock('/auth/register', 'post', options => {
	const { username, password } = JSON.parse(options.body);

	// 简单的用户名和密码验证
	if (!username || username.length < 3) {
		return {
			code: 400,
			message: '用户名至少需要3个字符',
			data: null,
		};
	}

	if (!password || password.length < 6 || password.length > 12) {
		return {
			code: 400,
			message: '密码长度需要在6到12个字符之间',
			data: null,
		};
	}

	// 注册成功
	const data = {
		userId: Random.id(),
		username: username,
	};
	return createResponse(200, '注册成功', data);
});

console.log('Mock服务已启动');
